package com.whu.exp1jsp.controller;

import com.sun.media.sound.SoftTuning;
import com.whu.exp1jsp.dao.UserDAO;
import com.whu.exp1jsp.pojo.UserSt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "loginServlet", value = "/login-servlet")
public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
        // 获取表单参数
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        UserDAO userDAO = new UserDAO();
        UserSt userSt = null;
        try {
            userSt = userDAO.selectUserByPhoneNum(account);
        }catch (SQLException e){
            request.setAttribute("error", e.getMessage());
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }

        if (userSt != null && userSt.getUserPassword().equals(password)) {
            // 登录成功
            HttpSession session = request.getSession();
            session.setAttribute("user", userSt);
            request.setAttribute("operation", "getProducts");
            request.getRequestDispatcher("products-servlet").forward(request, response);
        } else {
            // 登录失败，返回登录页面并显示错误信息
            request.setAttribute("errorMessage", "账号或密码错误");

            request.getRequestDispatcher("login.jsp").forward(request, response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }


}
